using Beauty.Net.JsonWebToken.Core;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace Beauty.Net.JsonWebToken;

/// <summary>
/// JWT功能使用示例
/// 注意：此示例类仅用于演示，实际项目中应根据需求使用
/// </summary>
public class ExampleUsage
{
    /// <summary>
    /// 运行示例测试
    /// </summary>
    public static void RunExample()
    {
        Console.WriteLine("===== Beauty.Net.JsonWebToken 功能测试 =====");
        
        // 1. 设置服务
        var serviceProvider = SetupServices();
        
        // 2. 获取JWT服务
        var jwtService = serviceProvider.GetRequiredService<IJwtService>();
        
        // 3. 测试创建和验证访问令牌
        TestAccessToken(jwtService);
        
        // 4. 测试刷新令牌功能
        TestRefreshToken(jwtService);
        
        // 5. 测试令牌过期检查
        TestTokenExpiration(jwtService);
        
        Console.WriteLine("\n===== 测试完成 =====");
    }
    
    /// <summary>
    /// 设置测试服务
    /// </summary>
    private static ServiceProvider SetupServices()
    {
        var services = new ServiceCollection();
        
        // 配置JWT服务
        services.AddJwtService(options =>
        {
            options.SecretKey = "TestSecretKey123456789012345678901234";
            options.Issuer = "TestIssuer";
            options.Audience = "TestAudience";
            options.AccessTokenExpirationMinutes = 30;
            options.RefreshTokenExpirationHours = 24;
        });
        
        return services.BuildServiceProvider();
    }
    
    /// <summary>
    /// 测试访问令牌功能
    /// </summary>
    private static void TestAccessToken(IJwtService jwtService)
    {
        Console.WriteLine("\n[测试访问令牌]");
        
        // 创建用户ID
        var userId = "test-user-123";
        
        // 创建自定义声明
        var customClaims = new Dictionary<string, object>
        {
            { "role", "admin" },
            { "username", "testuser" },
            { "department", "IT" }
        };
        
        // 创建访问令牌
        var accessToken = jwtService.CreateAccessToken(userId, customClaims);
        Console.WriteLine($"创建的访问令牌: {accessToken}");
        
        // 验证访问令牌
        var (isValid, validatedUserId, validatedClaims) = jwtService.ValidateAccessToken(accessToken);
        
        Console.WriteLine($"令牌验证结果: {(isValid ? "有效" : "无效")}");
        Console.WriteLine($"用户ID: {validatedUserId}");
        
        if (validatedClaims != null)
        {
            Console.WriteLine("自定义声明:");
            foreach (var claim in validatedClaims)
            {
                Console.WriteLine($"  - {claim.Key}: {claim.Value}");
            }
        }
        
        // 测试无效令牌
        var invalidToken = "invalid.token.here";
        var (invalidResult, _, _) = jwtService.ValidateAccessToken(invalidToken);
        Console.WriteLine($"无效令牌验证结果: {(invalidResult ? "有效" : "无效")}");
    }
    
    /// <summary>
    /// 测试刷新令牌功能
    /// </summary>
    private static void TestRefreshToken(IJwtService jwtService)
    {
        Console.WriteLine("\n[测试刷新令牌]");
        
        var userId = "refresh-test-user";
        
        // 创建刷新令牌
        var refreshToken = jwtService.CreateRefreshToken(userId);
        Console.WriteLine($"创建的刷新令牌: {refreshToken}");
        
        // 验证刷新令牌
        var (isValid, validatedUserId) = jwtService.ValidateRefreshToken(refreshToken);
        Console.WriteLine($"刷新令牌验证结果: {(isValid ? "有效" : "无效")}");
        Console.WriteLine($"用户ID: {validatedUserId}");
        
        // 使用刷新令牌获取新的访问令牌
        var newAccessToken = jwtService.RefreshAccessToken(refreshToken);
        Console.WriteLine($"刷新后获取的新访问令牌: {newAccessToken != null}");
        
        // 测试无效刷新令牌
        var invalidRefreshToken = "invalid.refresh.token";
        var invalidNewToken = jwtService.RefreshAccessToken(invalidRefreshToken);
        Console.WriteLine($"使用无效刷新令牌: {(invalidNewToken == null ? "正确拒绝" : "错误允许")}");
    }
    
    /// <summary>
    /// 测试令牌过期检查
    /// </summary>
    private static void TestTokenExpiration(IJwtService jwtService)
    {
        Console.WriteLine("\n[测试令牌过期检查]");
        
        var userId = "expiration-test-user";
        
        // 创建访问令牌
        var accessToken = jwtService.CreateAccessToken(userId);
        
        // 检查是否即将过期（应该返回false，因为刚创建）
        var isExpiringSoon = jwtService.IsTokenExpiringSoon(accessToken, 29); // 29分钟阈值
        Console.WriteLine($"令牌是否即将过期 (29分钟阈值): {isExpiringSoon}");
        
        // 检查无效令牌
        var invalidToken = "invalid.token.here";
        var invalidIsExpiring = jwtService.IsTokenExpiringSoon(invalidToken);
        Console.WriteLine($"无效令牌过期检查结果: {invalidIsExpiring}");
    }
    
    /// <summary>
    /// 主方法入口（用于直接运行测试）
    /// </summary>
    public static void Main()
    {
        RunExample();
        Console.WriteLine("\n按任意键退出...");
        Console.ReadKey();
    }
}